package com.zsoft.webmail.servlet.hainannet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.zsoft.webmail.*;
import com.zsoft.webmail.message.*;
import comm.http.upload.*;
import com.zsoft.webmail.Application;
import comm.util.Utils;
import com.zsoft.webmail.mimeutility.MimeUtility;
import com.zsoft.webmail.folder.*;

public class MailDecodeAttachServlet extends HttpServlet {
  //private static final String CONTENT_TYPE = Application.getProperty("ContentType");
  private static final String CONTENT_TYPE = "text/html";
  /**Initialize global variables*/
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }
  /**Process the HTTP Get request*/
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

comm.http.Request request1=new comm.http.Request(request,Application.getProperty("defaultInputCharset"));
    MemberAuthorization memberAuthToken=null ;
    HttpSession session=request.getSession();
    Object object = session.getAttribute("authBean");
    if(object==null){
      session.setAttribute("authBean",new com.zsoft.webmail.AuthBean(session.getId(),request.getRemoteAddr()));
      response.sendRedirect( "login.jsp" );
      return;
    }else{
      memberAuthToken = ((AuthBean)object).getMemberAuthToken();
      if(memberAuthToken==null){
        response.sendRedirect( "login.jsp" );
        return;
      }
    }


SmartUpload attachDownload =new SmartUpload();
//get parameters
String boxid=request1.getParameter("boxid");
String mid=request1.getParameter("mid");
String pid=request1.getParameter("pid");
String action=request1.getParameter("action");
if(action==null) action="view";

boxid=comm.util.FileUtils.getFilename(boxid);
mid=comm.util.FileUtils.getFilename(mid);

//get all relevant paths

String userPath=memberAuthToken.homePath;
char sep='/';
String webPath=memberAuthToken.webPath;
String msgPath;

if ( boxid != null )
{
        FolderList fl=null;
        try{
        fl=new FolderList(userPath+"/directory.cfg");
        }catch(Exception e){

        }
        msgPath = userPath+sep+fl.getValueById(boxid);
}
else
        msgPath = webPath;

Message msg=null;
try{
try{
msg = new Message(msgPath+sep+mid);
}catch(Exception e){

}

Header header=new Header(msgPath+sep+mid+".hdr");
String name=null;
String type=null;
try{
name=header.getPartName(pid);
if(name==null || name.trim().equals("")) name="ATTTMP.DAT";
name=comm.util.FileUtils.getFilename(name); //get filename
name=comm.util.StringUtils.replace(name,"\u0000","");
type=header.getPartType(pid);
if(type==null) type="";
if(type.equals("")) type=MimeUtility.getContentType(name);
}finally{
header.close();
}

//--start to download

// Initialization
attachDownload.initialize(super.getServletConfig(),request,response);


String downPath=webPath+sep+"download";
String downFileName=downPath+sep+mid+"_"+pid+"_"+name;
if(action.equalsIgnoreCase("view")){


  if(type.endsWith("html") || type.endsWith("htm")){

    downFileName=downPath+sep+mid+"_"+pid+"_secure_"+name;
    java.io.File file=new java.io.File(downFileName);
    if(!file.exists()){
      FileOutputStream fos=new FileOutputStream(downFileName);
      try{
        msg.saveHtmlPartSecureAs(pid, (OutputStream)fos);
      }catch(Exception e){
      }finally{
      fos.close();
      }
    }

  }else{
    if(type.trim().equalsIgnoreCase("text/plain")){
      downFileName=downPath+sep+mid+"_"+pid+"_secure_"+name;
      java.io.File file=new java.io.File(downFileName);
      if(!file.exists()){
        FileOutputStream fos=new FileOutputStream(downFileName);
        try{
          msg.savePlainPartSecureAs(pid, (OutputStream)fos);
        }catch(Exception e){
        }finally{
        fos.close();
        }
      }
      type="text/html";
    }else{
      java.io.File file=new java.io.File(downFileName);
      if(!file.exists()){
        FileOutputStream fos=new FileOutputStream(downFileName);
        try{
          msg.savePartAs(pid, (OutputStream)fos);
        }catch(Exception e){
        }finally{
        fos.close();
        }
      }
    }

  }

  msg.close();
  msg=null;
  attachDownload.downloadFile(downFileName,type,new String(name.trim().getBytes(),"ISO-8859-1"),true);

}else{

  FileOutputStream fos=new FileOutputStream(downFileName);
  try{
    msg.savePartAs(pid, (OutputStream)fos);
  }catch(Exception e){
  }finally{
  fos.close();
  }
  msg.close();
  msg=null;
  try{
      attachDownload.downloadFile(downFileName,type,new String(name.trim().getBytes(),"ISO-8859-1"));
  }catch(Exception e){

  }
}




//after download, we should delete the decoded file
/*
File delFileName=new File(downFileName);
delFileName.delete();

*/
}catch(Exception e){
}finally{
if(msg!=null)
  msg.close();
}

  }
  /**Process the HTTP Post request*/
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
  }
  /**Clean up resources*/
  public void destroy() {
  }
}